<?php

namespace Frieza\Modules\Statsign\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\service\advertisement\position\BizPositionStatSign;
use Biz\service\erp\Nippon;
use Doraemon\model\StatSign\StatSignModuleType;
use Doraemon\service\position\Api;
use Doraemon\service\position\PositionApi;
use Doraemon\service\statSign\StatSign;
use Doraemon\service\statSign\StatSign as sStatSign;
use Doraemon\tools\HhzEnv;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\StatSign\StatSign as mStatSign ;

class StatSignController extends Controller
{

    public function index(Request $request, Content $content)
    {

        $tab = new tab();

        $title = 'statSign列表';

        $tab->add($title, $this->listData($request));

        $link = admin_url(BizPositionStatSign::getRoute()->getListRoute());
        $message = [
            '新建的statSign全部由<a target="_blank" href="https://astrolabe.haohaozhu.me/?#/sensors/events"> 星盘·事件管理 </a>提供 ',
            ' <a target="_blank" href="'.$link.'"> 使用线上生成的配置 </a>, 覆盖对应文件',
            '检查类常量定义冲突,提交代码完成配置',
        ];
        $title = '提示';
        $icon = 'info';


        $html = \Doraemon\tools\Msg2Admin::html($title, implode('<br/>', $message), $icon);
        $content->body($html);

        return $content
            ->header('statSign管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }

    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $module_type = $request->input('module_type', '');
        $full_module = $request->input('full_module', '');
        $desc = $request->input('desc', '');
        $condition = [];
        if (!empty($module_type)) {
            $condition['module_type'] = $module_type;
        }
        if (!empty($full_module)) {
            $condition['full_module[~]'] = "%" . $full_module . "%";
        }
        if (!empty($desc)) {
            $condition['s_name[~]'] = "%" . $desc . "%";
        }

        $statSignValue = sStatSign::getList($condition, $page, $pageSize);
        $gridModel = new pGridDataModel($statSignValue['data'], $statSignValue['total'], ['perPage' => $pageSize]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $condition) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->paginate($gridModel->getPerPage());

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($condition) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($condition) {
                    $filter->equal('module_type', '模块类型')->select(StatSign::getModuletypeToArr())->default($condition['module_type']);
                    $filter->equal('desc', '描述');
                });

                $filter->column(1 / 2, function (Grid\Filter $filter) use ($condition) {
                    $filter->equal('full_module', '模块名称');
                });

                //条件展开
                if ($condition) $filter->expand();
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->append('<a class="fa fa-line-chart" href="javascript:layer.open({
            type: 2,
            title: \'CTR数据\',
            maxmin: true,
            shade: 0,
            area: [\'900px\', \'500px\'],
            content: \'' . $this->row->ctr . '\'
        });">CTR</a>');
            });

            $grid->column('id');
            $grid->column('s_name', '描述');

            $grid->column('app','展示的来源类型')->display(function($app){
                $format = [];
                foreach(sStatSign::APP_TYPES as $key => $value){
                    if ($key & $app) $format[] = $value;
                }
                return $format;
            })->label('default');

            $moduleTypeName = sStatSign::getModuletypeToArr();

            $grid->column('base_info', '基础信息')->display(function () use ($moduleTypeName) {
                $moduleType = $moduleTypeName[$this->module_type] ?? '-';
                $show = [
                    '模块类型 : ' . $moduleType,
                    '模块名称 : ' . sStatSign::formatLabel($this->full_module),
                    '展示样式 : ' . sStatSign::formatLabel($this->style),
                    '展示内容来源 : ' . sStatSign::formatLabel($this->display_source),
                ];
                return implode('<br/>', $show);
            });

            $grid->column('ext', '扩展信息')->display(function () use ($moduleTypeName) {
                $show = [];
                foreach ($this->ext as $k => $v) {
                    if (in_array($k, ['reason_type', 'display_source'])) {
                        $show[] = mStatSign::EXT_FIELD_MAP[$k] . " : " . sStatSign::formatLabel($v);
                    } else {
                        $show[] = $v . " : " . sStatSign::formatLabel($k);
                    }
                }
                return implode('<br/>', $show);
            });
            $grid->column('edittime', '操作时间')->display(function () {
                $show = [
                    '添加时间:' . ($this->addtime == '0000-00-00 00:00:00' ? '-' : $this->addtime),
                    '修改时间:' . ($this->edittime == '0000-00-00 00:00:00' ? '-' : $this->edittime),
                ];
                return implode('<br/>', $show);
            });
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id > 0 ? Admin::user()->find($this->admin_id)->name : '-';
            });
        });

        return $listGrid->render();

    }

    public function edit($id = 0, Content $content)
    {
        $tab = new Tab();
        $title = $id > 0 ? '编辑statSign' : '创建statSign';

        $tab->add("$title", $this->editAction($id));
        return $content
            ->header($title)
            ->breadcrumb(
                [
                    'text' => 'statSign列表',
                    'url'  => route('statSign.index')
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {

        if ($id > 0) {
            $info = sStatSign::getValueById($id);
            $form = new Form($info);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->html("<div class='' >")->plain();
            $form->checkbox('app', '展示的来源类型')->options(sStatSign::APP_TYPES)->default([sStatSign::APP_TYPE_APP]);
            $form->select('module_type', '模块类型')->options(sStatSign::getModuletypeToArr())->required();
            $form->radio('page', '页码')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
        $form->html('</div>')->plain();

        $form->html("<div class='bg-info' >")->plain();
            $form->text('module','模块名称')->required()->help('英文名称');
            $form->text('s_name','名称描述');
            $form->radio('s_index', '展示位置')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->checkbox('style','展示样式')->options(sStatSign::STYLE_TYPES);
            $form->checkbox('display_source','展示内容来源')->options(sStatSign::DISPLAY_SOURCE_TYPES)->default([sStatSign::DISPLAY_SOURCE_TYPE_PRIMAL]);
            $form->radio('config_id', '配置项id')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('config_group', '配置项的用户分群设置')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
        $form->html('</div>')->plain();
        // 单选框
            $form->radio('obj_uid', '内容主体的所有者uid')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('obj_id', '内容主体id')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('obj_type', '内容主体类型')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('activity_name', '活动名称')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('pos', '位置信息')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('url_type', '跳转链接类型')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('url', '跳转链接')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);

            $form->checkbox('reason_type', '展示原因类型')->options(sStatSign::REASON_TYPES);
            $form->radio('reason', '展示原因')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('s_from', '页面请求来源')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('key_word', '页面请求参数')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('relate_obj_type', '关联的内容主体类型')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('relate_obj_id', '关联的内容主体id')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);
            $form->radio('params', '附加信息')->options(mStatSign::IS_EXISTENCE)->default(mStatSign::IS_EXISTENCE_OFF);

        $form->action(route('statSign.save'));

        return $form;
    }

    public function save(Request $request)
    {
        $params = $request->all();

        try {

            if (HhzEnv::isAdmProduction()) sStatSign::writeModuleFile(true);

            $bool = mStatSign::action(function() use ($params){

                sStatSign::saveStatSign($params);

                return true;
            });

            if ($bool && HhzEnv::isAdmProduction()) sStatSign::writeModuleFile();

            return redirect(route('statSign.index'))->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } catch (\Exception $e) {
            return back()->with('error', new MessageBag([
                'title' => $e->getMessage()
            ]))->withInput();
        }
    }

    public function del($id = 0)
    {
        $status = true;
        $message = "删除成功";
        try {
            $info = sStatSign::getValueById($id);

            if (empty($info)) throw new \Exception('删除信息不存在');

            if ($info['s_status'] != StatSignModuleType::STATUS_NORMAL) throw new \Exception('信息已经被删除');

            sStatSign::delModule($id);

            \Doraemon\cache\PositionModule\StatSign::delItem($id);
            \Doraemon\cache\PositionModule\StatSign::delItem($info['full_module']);
        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        } finally {
            return response()->json(compact('status', 'message'));
        }
    }

    public function moduleTypeList(Request $request, Content $content)
    {
        $tab = new tab();

        $title = '模块类型列表';

        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $module_type = $request->input('module_type', '');
        $t_name = $request->input('t_name', '');

        $condition = [];
        if (!empty($module_type)) {
            $condition['module_type[~]'] = $module_type;
        }
        if (!empty($t_name)) {
            $condition['t_name[~]'] = "%" . $t_name . "%";
        }

        $statSignValue = sStatSign::getModuleTypeList($condition, $page, $pageSize);

        $gridModel = new pGridDataModel($statSignValue['data'],$statSignValue['total'], ['perPage' => $pageSize]);

        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $condition, $pageSize) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->paginate($pageSize);

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($condition) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($condition) {
                    $filter->equal('module_type', '模块类型标识');
                });

                $filter->column(1 / 2, function (Grid\Filter $filter) use ($condition) {
                    $filter->equal('t_name', '类型名称');
                });

                //条件展开
                if ($condition) $filter->expand();
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
            });

            $grid->column('id');
            $grid->column('module_type', '模块类型标识');
            $grid->column('t_name', '名称');
            $grid->column('addtime', '添加时间');
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id > 0 ? Admin::user()->find($this->admin_id)->name : '-';
            });
        })->render();

        $tab->add($title, $grid);
        
        return $content
            ->header('模块类型管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }

    public function editModuleType($id = 0, Content $content)
    {
        $tab = new Tab();

        $title = $id > 0 ? '编辑模块类型' : '创建模块类型';

        $tab->add("$title", $this->editModuletypeAction($id));
        return $content
            ->header('模块类型管理')
            ->breadcrumb(
                [
                    'text' => '模块类型列表',
                    'url'  => route('statSign.moduleTypeList')
                ],
                ['text' => $title]
            )
            ->body($tab);
    }

    private function editModuleTypeAction($id=0)
    {
        if ($id > 0) {
            $info = sStatSign::getModueltypeById($id);
            $form = new Form($info);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->text('module_type', '模块类型标识')->help('英文标识')->required();

        $form->text('t_name', '名称')->required();

        $form->action(route('statSign.moduleTypeSave'));

        return $form;
    }

    public function saveModuleType(Request $request)
    {

        $params = [
            'module_type' => $request->input('module_type', ''),
            't_name' => $request->input('t_name', ''),
        ];
        $id = $request->input('id', 0);
        $info = sStatSign::getModueltypeById($id);

        try {
            $changeType = $info['module_type'] != $params['module_type'];

            if (HhzEnv::isAdmProduction()) sStatSign::writeModuleTypeFile(true);

            if ($changeType && mStatSign::getCountByModuleType($info['module_type'])) throw new \Exception('已经有StatSign关联');

            $bool = mStatSign::action(function() use ($params, $id){

                sStatSign::saveModuleType($params, $id);

                return true;
            });

            if ($bool && HhzEnv::isAdmProduction()) sStatSign::writeModuleTypeFile();

            return redirect(route('statSign.moduleTypeList'))->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } catch (\Exception $e) {
            return back()->with('error', new MessageBag([
                'title' => $e->getMessage()
            ]))->withInput();
        }
    }

    public function delModuleType($id = 0)
    {
        $status = true;
        $message = "删除成功";
        try {
            $info = sStatSign::getModueltypeById($id);

            if (empty($info)) throw new \Exception('删除信息不存在');

            if ($info['t_status'] != StatSignModuleType::STATUS_NORMAL) throw new \Exception('信息已经被删除');

            if (HhzEnv::isAdmProduction()) sStatSign::writeModuleTypeFile(true);

            if (mStatSign::getCountByModuleType($info['module_type'])) throw new \Exception('已经有StatSign关联');

            $bool = mStatSign::action(function() use ($id) {

                sStatSign::delModuleType($id);

                return true;
            });

            if ($bool && HhzEnv::isAdmProduction()) sStatSign::writeModuleTypeFile();

        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        } finally {
            return response()->json(compact('status', 'message'));
        }
    }

}